﻿using System.IO.Ports;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BlazorSerialUpload.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {

        [HttpPost]
        //[RequestSizeLimit(10 * 1024 * 1024)] // 10 MB limit
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");

            string portName = "/dev/ttyUSB0"; // 修改为你的串口名称
            int baudRate = 9600; // 设置你的波特率

            using (var serialPort = new SerialPort(portName, baudRate))
            {
                serialPort.Open();
                await using (var stream = file.OpenReadStream())
                {
                    var buffer = new byte[4096];
                    long totalBytes = file.Length;
                    long totalBytesRead = 0;

                    while (true)
                    {
                        int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                            break;

                        serialPort.Write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;

                        // 在这里你可以选择保存进度或发送到客户端
                    }
                }
            }

            return Ok("File uploaded and written to serial port successfully.");
        }
    }
}
